<template>
  <div class="app-container" id="taskList">
    <h1 class="app-header">待办清单</h1>
    <!-- 添加新事项 -->
    <div class="center" style="display: flex; justify-content: center;">
      <vs-button @click="activeAdd = !activeAdd" style="background-color: rgb(137 171 158); box-shadow: none;">
        添加新事项
      </vs-button>
      <vs-dialog v-model="activeAdd">
        <template #header>
          <h4 class="not-margin">
            <b>设置新事项</b>
          </h4>
        </template>
        <div class="con-form">
          <vs-input v-model="tasks.title" placeholder="事项名" style="margin: 30px;align-items: center;"></vs-input>
          <vs-input type="date" v-model="tasks.startTime" label="开始时间" style="margin: 30px;align-items: center;"/>
          <vs-input type="date" v-model="tasks.endTime" label="结束时间" style="margin: 30px;align-items: center;"/>
          <div style="display: flex;margin: 30px;align-items: center;justify-content: center;">
            <vs-select v-model="value" placeholder="紧急程度" label="紧急程度" @change="handleChange(value)">
              <vs-option label="1" value="1">
                特急
              </vs-option>
              <vs-option label="2" value="2">
                紧急
              </vs-option>
              <vs-option label="3" value="3">
                一般
              </vs-option>
              <vs-option label="4" value="4">
                轻松
              </vs-option>
            </vs-select>
          </div>
        </div>
        <template #footer>
          <div class="footer-dialog">
            <vs-button block type="submit" class="add-btn" @click="newItem" color="rgb(137,171,158)">
              添加
            </vs-button>
          </div>
        </template>
      </vs-dialog>
    </div>
    <!-- 事项列表 -->
    <ul class="task-list">
      <li class="task-list-item" v-for="task in tasks" v-bind:key="task.taskid" :class="getTaskItemClass(task)">
        <!--完成事项 -->
        <label class="task-list-item-label">
          <input type="checkbox" :checked="task.status" :disabled="isCheckboxDisabled(task)" @change="completeItem(task)" >
          <span>{{ task.title }}</span>
          <vs-dialog width="550px" not-center v-model="activeComplete[task.title]" not-close>
            <template #header>
              <h4 class="not-margin">
                <b>完成事项总结</b>
              </h4>
            </template>
            <div class="con-content" style="display: flex; justify-content: center;">
              <!-- <vs-input type="text" v-model="task.summary" style="width: 200px;"/> -->
              <textarea placeholder="请输入总结..." v-model="task.summary" style="height: 150px; width: 400px;"></textarea>
            </div>
            <template #footer>
              <div class="con-footer">
                <vs-button @click="sumItem(task)" transparent style="margin-left: auto; --vs-color: 137,171,158;">
                  完成
                </vs-button>
              </div>
            </template>
          </vs-dialog>
        </label>
        <!-- 查看详情 -->
        <vs-button @click="setActiveDetail(task.title, true, task)" style="margin-left: auto; background-color:#228b5f30;box-shadow: none;">
        Detail
        </vs-button>
        <vs-dialog width="550px" not-center v-model="activeDetail[task.title]">
        <template #header>
          <h4 class="not-margin">
            <b>事项名：{{ task.title }}</b>
          </h4>
        </template>
        <div class="con-content">
          <p>开始时间：{{ task.startTime }}</p>
          <p>结束时间：{{ task.endTime }}</p>
          <p>紧急程度：{{ task.level }}</p>
          <p>完成总结：{{ task.summary }}</p>
        </div>
        <template #footer>
          <div class="con-footer">
            <vs-button @click="activeDetail[task.title]=false" transparent style="margin-left: auto; --vs-color: 137,171,158;">
              Ok
            </vs-button>
          </div>
        </template>
      </vs-dialog>
        <!-- 删除事项 -->
        <span @click="delItem(task)" class="delete-btn" title="Delete Task">{{ task.del }}</span>
        <!-- 修改事项 -->
        <div style="display: flex; justify-content: center;">
          <input type="submit" value="" class="submit-task" title="Edit Task" @click="setActiveEdit(task.title, true)">
          <vs-dialog v-model="activeEdit[task.title]">
            <template #header>
              <h4 class="not-margin">
                <b>修改事项</b>
              </h4>
            </template>
            <div class="con-form">
              <vs-input v-model="task.newName" placeholder="事项名" style="margin: 30px;align-items: center;"></vs-input>
              <vs-input type="date" v-model="task.newStartTime" label="开始时间" style="margin: 30px;align-items: center;"/>
              <vs-input type="date" v-model="task.newEndTime" label="结束时间" style="margin: 30px;align-items: center;"/>
              <div style="display: flex;margin: 30px;align-items: center;justify-content: center;">
                <vs-select v-model="value" placeholder="紧急程度" label="紧急程度" @change="handleNewChange(task,value)">
                  <vs-option label="1" value="1">
                    特急
                  </vs-option>
                  <vs-option label="2" value="2">
                    紧急
                  </vs-option>
                  <vs-option label="3" value="3">
                    一般
                  </vs-option>
                  <vs-option label="4" value="4">
                    轻松
                  </vs-option>
                </vs-select>
              </div>
            </div>
            <template #footer>
              <div class="footer-dialog">
                <vs-button block type="submit" class="add-btn" @click="editItem(task)" color="rgb(137,171,158)">
                  修改
                </vs-button>
              </div>
            </template>
          </vs-dialog>
        </div>
      </li>
    </ul>
  </div>
</template>

<script scoped>
import axios from 'axios'
export default {
  data: () => ({
    tasks: [
      // // 初始任务列表
      // { title: '任务1', startTime: '2023-06-01', endTime: '2023-06-05', newName: '', newStartTime: '', newEndTime: '', level: 1 },
      // { title: '任务2', startTime: '2023-06-03', endTime: '2023-06-07', newName: '', newStartTime: '', newEndTime: '', level: 1 },
      // { title: '任务3', startTime: '2023-06-06', endTime: '2023-06-10', newName: '', newStartTime: '', newEndTime: '', level: 1 }
      // // 从后端请求获取当前用户任务列表 showAllItem()
    ],
    activeAdd: false, // 控制添加新事项对话框的显示和隐藏
    activeEdit: {}, // 控制每个修改事项对话框的显示和隐藏，使用对象以便为每个事项维护独立的状态
    activeDetail: {}, // 控制每个详情对话框的显示和隐藏
    activeComplete: {}, // 控制每个完成对话框的显示和隐藏
    allTask: [],
    value: '',
    tasksUpdated: 0 // 用于触发重新渲染的计数器
  }),
  methods: {
    formatDateTime (date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    setActiveEdit (taskName, value) {
      if (!this.activeEdit.hasOwnProperty(taskName)) {
        this.$set(this.activeEdit, taskName, false)
      }
      this.activeEdit[taskName] = value
      console.log(taskName, this.activeEdit, value)
    },
    setActiveDetail (taskName, value, task) {
      if (!this.activeDetail.hasOwnProperty(taskName)) {
        this.$set(this.activeDetail, taskName, false)
      }
      this.activeDetail[taskName] = value
      console.log(task.taskid, task.title, task.startTime, task.endTime, task.level, task.status)
    },
    setActiveComplete (taskName, value, task) {
      if (!this.activeComplete.hasOwnProperty(taskName)) {
        this.$set(this.activeComplete, taskName, false)
      }
      this.activeComplete[taskName] = value
      console.log(task.taskid, task.title, task.startTime, task.endTime, task.level, task.status)
    },
    showAllItem () {
      // 向后端发送get请求
      console.log(this.$store.state.userinfo.account)
      axios.get('/api/alltask', {
        params: {
          account: this.$store.state.userinfo.account
        }
      })
        .then(response => {
          // console.log(response.data.data.task[0].Title)
          this.allTask = response.data.data.task
          // 将获取事项加入任务列表
          for (let index = 0; index < this.allTask.length; index++) {
            console.log('加入待办' + this.allTask[index].Title)
            this.tasks.push({
              taskid: this.allTask[index].Id,
              title: this.allTask[index].Title,
              startTime: this.allTask[index].StartTime,
              endTime: this.allTask[index].EndTime,
              level: this.allTask[index].Level,
              status: this.allTask[index].Status,
              summary: this.allTask[index].Summary
            })
          }
        })
        .catch(function (err) {
          console.log('待办获取失败' + err)
        })
    },
    newItem () {
      if (!this.tasks.title || !this.tasks.startTime || !this.tasks.endTime || !this.tasks.level) {
        // 显示警告信息
        alert('所有项目必填，不可为空！')
        return
      }
      if (this.tasks.startTime > this.tasks.endTime) {
        // 显示警告信息
        alert('开始时间必须早于结束时间')
        return
      }
      if (new Date(this.tasks.endTime) <= new Date()) {
        // 显示警告信息
        alert('结束时间必须晚于当前时间')
        return
      }
      // 将新增事项传入数据库
      const formData = new FormData()
      formData.append('account', this.$store.state.userinfo.account)
      formData.append('title', this.tasks.title)
      formData.append('starttime', this.formatDateTime(new Date(this.tasks.startTime)))
      formData.append('endtime', this.formatDateTime(new Date(this.tasks.endTime)))
      formData.append('level', this.tasks.level)
      for (var value of formData.values()) {
        console.log(value)
      }
      // 发送POST请求到后端
      axios.post('/api/create', formData)
        .then(response => {
          // 创建成功处理响应
          console.log('返回taskid' + response.data.data.taskid)
          this.tasks.taskid = response.data.data.taskid
          // 可以在这里进行重定向或其他操作
          // this.$store.dispatch('saveNewTask', response.data.taskid)
          // 将新增事项加入任务列表
          this.tasks.push({
            title: this.tasks.title,
            startTime: this.tasks.startTime,
            endTime: this.tasks.endTime,
            level: this.tasks.level,
            taskid: this.tasks.taskid,
            status: 0
          })
          console.log('新增待办' + this.tasks.taskid, this.tasks.title, this.tasks.startTime, this.tasks.endTime, this.tasks.level)
          // 清空输入框
          this.tasks.title = ''
          this.tasks.startTime = ''
          this.tasks.endTime = ''
          this.tasks.level = ''
          this.value = ''
        })
        .catch(error => {
          console.error('创建待办失败' + error)
        })
    },
    // 编辑已有事项
    editItem (task) {
      if (!task.newName || !task.newStartTime || !task.newEndTime || !task.newlevel) {
        // 显示警告信息
        alert('所有项目必填，不可为空！')
        return
      }
      if (task.newStartTime > task.newEndTime) {
        // 显示警告信息
        alert('开始时间必须早于结束时间')
        return
      }
      if (new Date(this.tasks.endTime) <= new Date()) {
        // 显示警告信息
        alert('结束时间必须晚于当前时间')
        return
      }
      const index = this.tasks.indexOf(task)
      this.activeEdit[task.title] = false
      if (index !== -1) {
        this.tasks[index].title = task.newName
        this.tasks[index].startTime = task.newStartTime
        this.tasks[index].endTime = task.newEndTime
        this.tasks[index].level = task.newlevel
        this.tasks[index].status = 0
        this.tasks[index].summary = ''

        // 修改后的数值传入数据库
        const formData = new FormData()
        formData.append('taskid', this.tasks[index].taskid)
        formData.append('title', this.tasks[index].title)
        formData.append('starttime', this.formatDateTime(new Date(this.tasks[index].startTime)))
        formData.append('endtime', this.formatDateTime(new Date(this.tasks[index].endTime)))
        formData.append('level', this.tasks[index].level)
        for (var value of formData.values()) {
          console.log(value)
        }
        // 发送PUT请求到后端
        axios.put('/api/edit', formData)
          .then(response => {
            // 修改成功处理响应
            console.log('修改待办成功' + response)
          })
          .catch(error => {
            console.error('编辑待办失败' + error)
          })
        task.newName = '' // 清空输入框
        task.newStartTime = ''
        task.newEndTime = ''
        this.value = ''
        console.log(task.title + ' task was edited ')
      }
    },

    delItem (task) {
      console.log('Received task to delete:', this.tasks.indexOf(task), task.taskid, task.title)
      // 发送DELETE请求到后端
      const formData = new FormData()
      formData.append('taskid', task.taskid)
      for (var value of formData.values()) {
        console.log(value)
      }
      axios.delete('/api/delete', {data: formData})
        .then(response => {
          console.log('删除待办成功' + response.data)
          this.tasks.splice(this.tasks.indexOf(task), 1)
        })
        .catch(error => {
          console.log('删除待办失败' + error)
        })
    },
    // 设置事项为完成状态
    completeItem (task) {
      if (task.status === 0) { // 当前任务为未完成任务
        this.setActiveComplete(task.title, true, task)
        // 发送PUT请求到后端
        const formData = new FormData()
        formData.append('taskid', task.taskid)
        axios.put('/api/complete', formData)
          .then(response => {
            console.log('完成待办成功' + response.data)
            console.log('Received task to complete:', task.taskid, task.title, task.status)
            console.log('当前任务状态' + task.status)
          })
          .catch(error => {
            console.log('完成待办失败' + error)
          })
        task.status = 1// 设置为选中状态
      } else { // 已完成任务，阻止取消选中操作
        this.$nextTick(() => {
          task.status = 1 // 保持复选框的选中状态
        })
      }
      task.status = true // 保持复选框的选中状态
    },
    // 总结待办
    sumItem (task) {
      // 发送POST请求到后端
      const formData1 = new FormData()
      formData1.append('taskid', task.taskid)
      formData1.append('summary', task.summary)
      axios.post('/api/summary', formData1)
        .then(response => {
          console.log('总结待办成功' + response.data)
          console.log('Received task to summarize:', task.taskid, task.title, task.summary)
        })
        .catch(error => {
          console.log('完成待办失败' + error)
        })
      this.activeComplete[task.title] = false
    },
    // 处理事项等级变化
    handleChange (value) {
      if (value === '1') {
        this.tasks.level = 1
      }
      if (value === '2') {
        this.tasks.level = 2
      }
      if (value === '3') {
        this.tasks.level = 3
      }
      if (value === '4') {
        this.tasks.level = 4
      }
      console.log(this.tasks.title, this.tasks.level)
    },
    handleNewChange (task, value) {
      if (value === '1') {
        task.newlevel = 1
      }
      if (value === '2') {
        task.newlevel = 2
      }
      if (value === '3') {
        task.newlevel = 3
      }
      if (value === '4') {
        task.newlevel = 4
      }
      console.log(task.title, task.newlevel)
    },
    getTaskItemClass (task) {
      if (task.status === 2) {
        return 'expired' // 自定义样式类名，用于表示过期事项
      } else if (task.level === 1) {
        return 'level-1' // 自定义样式类名，用于表示级别1的事项
      } else if (task.level === 2) {
        return 'level-2' // 自定义样式类名，用于表示级别2的事项
      } else if (task.level === 3) {
        return 'level-3' // 自定义样式类名，用于表示级别3的事项
      } else if (task.level === 4) {
        return 'level-4' // 自定义样式类名，用于表示级别3的事项
      } else {
        return '' // 默认样式类，或者根据需要返回其他样式类
      }
    }
  },
  created () {
    this.showAllItem()
  },
  computed: {
    isCheckboxDisabled () {
      return function (task) {
        return task.status === 1 || task.status === 2 // 如果任务已完成或过期，则禁用复选框
      }
    }
  }
}
</script>

<style scoped>
@import url("https://fonts.googleapis.com/css?family=DM+Sans:400,500,700&display=swap");

* {
  box-sizing: border-box;
}

input {
  outline: none;
}

ul {
  list-style: none;
  padding: 0;
}

.not-margin {
  margin: 0px;
  font-weight: normal;
  padding: 10px;
}

.con-form {
  width: 100%;
}

.con-form .flex {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.con-form .flex a {
  font-size: 0.8rem;
  opacity: 0.7;
}

.con-form .flex a:hover {
  opacity: 1;
}

.con-form .vs-checkbox-label {
  font-size: 0.8rem;
}

.con-form .vs-input-content {
  margin: 10px 0px;
  width: calc(100%);
}

.con-form .vs-input-content .vs-input {
  width: 100%;
}

.footer-dialog {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  width: calc(100%);
}

.footer-dialog .vs-button {
  margin: 0px;
  align-content: space-around;
  --vs-color: 137,171,158;
}

.app-container {
  border-radius: 8px;
  width: 100%;
  max-width: 500px;
  max-height: 100%;
  background-color: #647e60ca;
  padding: 24px;
  overflow: auto;
  flex-grow: 1;
}

.app-header {
  font-size: 20px;
  line-height: 32px;
  margin: 0 0 12px 0;
  color: #fff;
}

.submit-task {
  width: 32px;
  height: 32px;
  flex-shrink: 0;
  border: none;
  background: var(--add-button);
  color: #fff;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%23ffffff' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='feather feather-plus'%3E%3Cline x1='12' y1='5' x2='12' y2='19'/%3E%3Cline x1='5' y1='12' x2='19' y2='12'/%3E%3C/svg%3E");
  background-size: 18px;
  background-position: center;
  background-repeat: no-repeat;
  border-radius: 50%;
  cursor: pointer;
  box-shadow: 0 0 12px 0 var(--add-button-shadow);
}

.add-task {
  height: 40px;
  font-size: 14px;
  display: flex;
}

.task-input {
  border-right: none;
  width: 100%;
  padding: 0 4px;
  outline: none;
  border: none;
  border-bottom: 1px solid #fff;
  background-color: transparent;
  margin-right: 12px;
  color: #fff;
  box-shadow: none;
  border-radius: 0;
}

.task-input:placeholder {
  color: #fff;
}

.task-list-item {
  background-color: #0b040463;
  border-radius: 4px;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  align-content: center;
  padding: 8px;
}
.level-1 {
  background-color: #ff6363a8; /* 设置背景颜色为红色 */
}
.level-2 {
  background-color: #f7ac49bd; /* 设置背景颜色为橙色 */
}
.level-3 {
  background-color: #84fbb0a7; /* 设置背景颜色为橙色 */
}
.level-4 {
  background-color: #72c1f9bf; /* 设置背景颜色为橙色 */
}
@keyframes blink {
        0% {
            opacity: 1;
        }
        50% {
            opacity: 0;
        }
        100% {
            opacity: 1;
        }
    }

/* 应用闪烁动画到组件 */
.expired {
    animation: blink 2s infinite; /* 持续时间和重复次数可以根据需要进行调整 */
}
.task-list-item input {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  border: 1px solid #fff;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='feather feather-check' stroke='%23fff'%3E%3Cpolyline points='20 6 9 17 4 12'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: center;
  background-size: 0;
  transition: 0.2s;
  margin-right: 8px;
  flex-shrink: 0;
  margin-top: 4px;
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
}

.task-list-item input:hover {
  border-color: var(--checkbox-color);
  box-shadow: 0 0 0 3px var(--checkbox-shadow);
}

.task-list-item input:checked {
  background-size: 10px;
  border: 1px solid var(--checkbox-color);
  background-color: var(--checkbox-color);
}

.task-list-item input:checked+span {
  color: rgba(255, 255, 255, 0.5);
  -webkit-text-decoration: line-through rgba(255, 255, 255, 0.8);
  text-decoration: line-through rgba(255, 255, 255, 0.8);
}

.task-list-item-label {
  display: flex;
  align-items: flex-start;
  color: #fff;
  margin-right: 8px;
  font-size: 14px;
  line-height: 24px;
  position: relative;
  transition: 0.2s;
  cursor: pointer;
}
.task-list-item .submit-task {
  width: 20px;
  height: 20px;
  padding: 0%;
  margin: 5px;
  flex-shrink: 0;
  border: none;
  color: #ff0000;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%23ffffff' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='feather feather-plus'%3E%3Cline x1='12' y1='5' x2='12' y2='19'/%3E%3Cline x1='5' y1='12' x2='19' y2='12'/%3E%3C/svg%3E");
  background-size: 15px;
  background-position: center;
  background-repeat: no-repeat;
  border-radius: 50%;
  cursor: pointer;
}

.delete-btn {
  margin-left: 0;
  display: block;
  width: 16px;
  height: 16px;
  background-repeat: no-repeat;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%23ff3d46' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='feather feather-trash-2'%3E%3Cpolyline points='3 6 5 6 21 6'/%3E%3Cpath d='M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2'/%3E%3Cline x1='10' y1='11' x2='10' y2='17'/%3E%3Cline x1='14' y1='11' x2='14' y2='17'/%3E%3C/svg%3E");
  background-size: 16px;
  background-position: center;
  cursor: pointer;
}

@supports (-webkit-appearance: none) or (-moz-appearance: none) {

  input[type=checkbox],
  input[type=radio] {
    -webkit-appearance: none;
    -moz-appearance: none;

  }
}
</style>
